Skip to content

Make the getMessage function for the javascript example more robust. #39672

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 14 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -244,27 +244,20 @@ You can quickly get started sending and receiving messages with this NodeJS code

import fs from "node:fs/promises";

const _r = rs=>_rs_rp = rs; let _rs_rp, _rp = null; // read promise
async function getMessage() {
while (_rp) await _rp; // wait for previous reads
_rp = new Promise(_r); // make any further calls to getMessage wait
const input = await fs.open("/dev/stdin");
const header = new Uint32Array(1);
await readFullAsync(1, header);
const message = await readFullAsync(header[0]);
await input.read(header);
const message = new Uint8Array(header[0]);
await input.read(message);
await input.close();
_rs_rp(); _rp = null; // allow the next getMessage call to proceed
return message;
}

async function readFullAsync(length, buffer = new Uint8Array(65536)) {
const data = [];
while (data.length < length) {
const input = await fs.open("/dev/stdin");
const { bytesRead } = await input.read({ buffer });
await input.close();
if (bytesRead === 0) {
break;
}
data.push(...buffer.subarray(0, bytesRead));
}
return new Uint8Array(data);
}

async function sendMessage(message) {
const header = Buffer.from(new Uint32Array([message.length]).buffer);
const stdout = process.stdout;
Expand Down
Loading